package com.lxr.activity;


	import java.util.ArrayList;
import java.util.HashMap;
	import java.util.List;  
    import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.DialogInterface;
    import android.content.Intent;
	import android.content.pm.ActivityInfo;  
import android.graphics.PointF;
	import android.os.Bundle;  
import android.os.StrictMode;
import android.text.TextUtils;
	import android.util.Log;  
	import android.view.View;  
	import android.view.Window;  
	import android.view.View.OnClickListener;  
    import android.widget.AdapterView;
	import android.widget.ArrayAdapter;
    import android.widget.Button;  
import android.widget.EditText;
	import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

    import android.widget.AdapterView.OnItemClickListener;
import android.app.Activity;
import android.app.AlertDialog;
	import android.app.ListActivity; 

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.XmlDom;
	import com.wxq.draw.DrawDBTool;
import com.wxq.schoolmap.DrawActivity;
import com.wxq.schoolmap.R;
import com.wxq.schoolmap.SpotDetailActivity;


	public class SiteListActivity extends Activity {
		private final static String TAG = "SiteListActivity";  
	    private Button btnsearch;
	    private EditText editsearch;
	    private String FloorName;
	    private String MallDBpath;
	    private DrawDBTool dbTool;
	    private ListView sitelist;
	    private List<Map<String,Object>> nameList;
	    AQuery aqt;  
	    
	    @Override  
	    public void onCreate(Bundle savedInstanceState) {  
	    	super.onCreate(savedInstanceState);
	        setContentView(R.layout.site_list);
	        Intent intent=getIntent();
	        Bundle bundle=intent.getExtras();
	        FloorName=bundle.getString("FloorName");
	        MallDBpath=bundle.getString("MallDBpath");
	        Log.i(TAG,FloorName+"lllllllllllllll");
	        dbTool = new DrawDBTool(this);
	        dbTool.setDBpath(MallDBpath);     
	        editsearch = (EditText) findViewById(R.id.editTextsearch);
	        sitelist = (ListView) findViewById(R.id.sitelist);
	        fillFloorsName();   
	        
	        aqt= new AQuery(this);
	        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
		    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
		    
		    
	        btnsearch=(Button) findViewById(R.id.search_site);
	        btnsearch.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialogShowbuilding();
				}
			});
	         
	        
	        sitelist.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					Intent resultIntent = new Intent();  
					
					float xx,yy;
					if(nameList.get(position).containsKey("parent_unit_id")){
						Log.d("lxr","onItemClick:ohyeah im get in!!!!");
						String unit_id=nameList.get(position).get("parent_unit_id").toString();
						String floor_id=nameList.get(position).get("floor_id").toString();
						Log.d("lxr","onItemClick: "+ unit_id+"   "+floor_id);
						resultIntent.putExtra("unit_id",unit_id);  
						resultIntent.putExtra("floor_id",floor_id);  
					}
				    xx=Float.parseFloat(nameList.get(position).get("Coord_X").toString());
					yy=Float.parseFloat(nameList.get(position).get("Coord_Y").toString());
					Log.d("lxr", "onItemClick: "+xx+"   "+yy);
					resultIntent.putExtra("X",xx);  
					resultIntent.putExtra("Y",yy);  
					
					setResult(RESULT_OK, resultIntent);  
					SiteListActivity.this.finish();  
					//finish();
				}});
	    }  
	      	    

	    
	    public void fillFloorsName() {
			nameList = dbTool.getSiteNames(FloorName);
			SimpleAdapter adapter = new SimpleAdapter(this, nameList, R.layout.site_list_item, new String[] { "CompanyName", "Coord_X", "Coord_Y" }, new int[] { R.id.sitename,R.id.siteX, R.id.siteY });
			sitelist.setAdapter(adapter);
			dbTool.close();
		}
	  
	    public void searchmapXML(String key) {
	    	nameList = new ArrayList<Map<String,Object>>();	
	    	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	    	dbTool.close();
	    	try {
	        	DocumentBuilder builder = factory.newDocumentBuilder();
	        	//String url="http://10.103.240.118:8080/buptmapv1/spot!search?format=xml&spot="+key+"&place=&type=&client=824&vkey=FFE58998-B203-B44E-A95B-8CA2D6CBCD65";
	        	 String url="http://10.3.240.9:8080/vmap/spot!search?format=xml&spot="+key+"&place=&type=&client=824&vkey=FFE58998-B203-B44E-A95B-8CA2D6CBCD65";
	        	
	        	 Log.d("lxr",url);
	        	Document dom = builder.parse(url);
	    	    Element root = dom.getDocumentElement();
	    	    NodeList items = root.getElementsByTagName("unit");//查找所有person节点
	    		
	    	  String x = null,y = null,unit_name = null,floor_id = null,parent_unit_id = null,parent_unit_name = null;
	    	  for (int i = 0; i < items.getLength(); i++) { 
	    		Element personNode = (Element) items.item(i);
	        	Map<String, Object> map = new HashMap<String, Object>();
	        	NodeList childsNodes = personNode.getChildNodes();
	         	for (int j = 0; j < childsNodes.getLength(); j++) {
	            	Node node = (Node) childsNodes.item(j); //判断是否为元素类型          	
	            	if(node.getNodeType() == Node.ELEMENT_NODE){ 
	             		Element childNode = (Element) node;
	    	        	if ("x".equals(childNode.getNodeName())) { 
	            		   x=childNode.getFirstChild().getNodeValue();  
	            		   map.put("Coord_X",x);
	            	   } else if ("y".equals(childNode.getNodeName())) {
	    	        	  y=childNode.getFirstChild().getNodeValue();
	    	        	  map.put("Coord_Y",y);
	            	   } else if ("floor_id".equals(childNode.getNodeName())) {
	            		   floor_id=childNode.getFirstChild().getNodeValue();
	    	        	  map.put("floor_id",floor_id);  
	    	           }else if ("unit_name".equals(childNode.getNodeName())) {
		    	    	   unit_name= childNode.getFirstChild().getNodeValue();
			    	    }else if ("parent_unit_name".equals(childNode.getNodeName())) {
	    	        	   parent_unit_name=childNode.getFirstChild().getNodeValue();
	    	        	   map.put("unit_name",parent_unit_name+":"+unit_name);
	    	           }else if ("parent_unit_id".equals(childNode.getNodeName())) {
	    	        	   parent_unit_id=childNode.getFirstChild().getNodeValue();
		    	          map.put("parent_unit_id",parent_unit_id);
		    	       }	 	
	            	}	
	    	   }
	         	nameList.add(map);
	         	//Log.d("lxr",(String) map.get("x")+(String) map.get("y")+(String) map.get("floor_id")+(String) map.get("unit_name")); 
	    	}
	    	} catch (Exception e) {
	    	e.printStackTrace();
	    	}
	    	if(nameList.isEmpty()){
		    	Toast toast = Toast.makeText(SiteListActivity.this, "没有搜索到任何‘"+editsearch.getText().toString()+"’相关的内容，请重新搜索", Toast.LENGTH_SHORT); 
		    	  toast.setGravity(0|0, 80, 80); 
		    	  toast.setMargin(-0.5f, 0f); 
		    	  toast.show();
			}else{
				SimpleAdapter adapter = new SimpleAdapter(SiteListActivity.this, nameList, R.layout.site_list_item, new String[] { "unit_name","Coord_X", "Coord_Y" }, new int[] { R.id.sitename,R.id.siteX, R.id.siteY });
				sitelist.setAdapter(adapter);
			}
	    	}
	    
	/*
	    public void searchmapXML(String key){        
	    	   String url="http://10.103.241.212:8080/vmap/spot!search?format=xml&spot="+key+"&place=&type=&client=824&vkey=FFE58998-B203-B44E-A95B-8CA2D6CBCD65";
		     // url="http://10.103.241.245/nnn.xml";
	    	  // url="http://10.103.240.118:8080/buptmapv1/spot!search?format=xml&spot="+key+"&city=&type=&client=824&vkey=FFE58998-B203-B44E-A95B-8CA2D6CBCD65";
		      Log.d("lxr", url);
	    	   aqt.ajax(url, XmlDom.class, this, "sitecallback");    
	    	   
		}
		
		public void sitecallback(String url, XmlDom xml, AjaxStatus status){
			Log.d("lxr", "sitecallback");
			nameList = new ArrayList<Map<String,Object>>();	
			Element root = xml.getElement();
    	    NodeList items = root.getElementsByTagName("unit");
    	  String x = null,y = null,unit_name = null,floor_id = null,parent_unit_id = null,parent_unit_name = null;
    	  for (int i = 0; i < items.getLength(); i++) { 
    		Element personNode = (Element) items.item(i);
        	Map<String, Object> map = new HashMap<String, Object>();
        	NodeList childsNodes = personNode.getChildNodes();
         	for (int j = 0; j < childsNodes.getLength(); j++) {
            	Node node = (Node) childsNodes.item(j);	
            	if(node.getNodeType() == Node.ELEMENT_NODE){ 
             		Element childNode = (Element) node;
    	        	if ("x".equals(childNode.getNodeName())) { 
            		   x=childNode.getFirstChild().getNodeValue();  
            		   map.put("Coord_X",x);
            	   } else if ("y".equals(childNode.getNodeName())) {
    	        	  y=childNode.getFirstChild().getNodeValue();
    	        	  map.put("Coord_Y",y);
            	   } else if ("floor_id".equals(childNode.getNodeName())) {
            		   floor_id=childNode.getFirstChild().getNodeValue();
    	        	  map.put("floor_id",floor_id);  
    	           }else if ("unit_name".equals(childNode.getNodeName())) {
	    	    	   unit_name= childNode.getFirstChild().getNodeValue();
		    	    }else if ("parent_unit_name".equals(childNode.getNodeName())) {
    	        	   parent_unit_name=childNode.getFirstChild().getNodeValue();
    	        	   map.put("unit_name",parent_unit_name+":"+unit_name);
    	           }else if ("parent_unit_id".equals(childNode.getNodeName())) {
    	        	   parent_unit_id=childNode.getFirstChild().getNodeValue();
	    	          map.put("parent_unit_id",parent_unit_id);
	    	       }	 	
            	}	
    	   }
         	nameList.add(map);
         	Log.d("lxr",(String) map.get("x")+(String) map.get("y")+(String) map.get("floor_id")+(String) map.get("unit_name"));
    	}
    	  if(nameList.isEmpty()){
		    	Toast toast = Toast.makeText(SiteListActivity.this, "没有搜索到任何‘"+editsearch.getText().toString()+"’相关的内容，请重新搜索", Toast.LENGTH_SHORT); 
		    	  toast.setGravity(0|0, 80, 80); 
		    	  toast.setMargin(-0.5f, 0f); 
		    	  toast.show();
			}else{
				SimpleAdapter adapter = new SimpleAdapter(SiteListActivity.this, nameList, R.layout.site_list_item, new String[] { "unit_name","Coord_X", "Coord_Y" }, new int[] { R.id.sitename,R.id.siteX, R.id.siteY });
				sitelist.setAdapter(adapter);
			}
    	  
		}
	   */
		    private void dialogShowbuilding() {   
		    new AlertDialog.Builder(this)  
		    .setTitle("搜索关键词")  
		    .setMessage("请选择您的搜索范围")  
		    .setPositiveButton  
		            ("搜索当前地图", new DialogInterface.OnClickListener()  
		                { public void onClick(DialogInterface dialog, int which) 
		                    {       
			                	nameList=dbTool.SearchSiteNames(FloorName,editsearch.getText().toString());
								SimpleAdapter adapter = new SimpleAdapter(SiteListActivity.this, nameList, R.layout.site_list_item, new String[] { "CompanyName", "Coord_X", "Coord_Y" }, new int[] { R.id.sitename,R.id.siteX, R.id.siteY });
								sitelist.setAdapter(adapter);
								dbTool.close();
		                    }})
		    .setNegativeButton  
		            ("搜索全校", new DialogInterface.OnClickListener()  
		                { public void onClick(DialogInterface dialog, int which){
		                	searchmapXML(editsearch.getText().toString());
		                	//searchmapXML(editsearch.getText().toString());
		                }})  
		    .show();  
		}  
		    
	    @Override
		protected void onPause() {
			dbTool.close();
			super.onPause();
		}	
	    @Override
		protected void onDestroy() {
			dbTool.close();
			super.onDestroy();
		}	
	}  